/**
 * @filename SysUserController.java
 */
package com.liupf.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.liupf.common.utils.Constants;
import com.liupf.common.utils.MD5Util;
import com.liupf.domain.City;
import com.liupf.domain.SysUser;
import com.liupf.domain.Tel;
import com.liupf.domain.TelPrice;

/**
 * @description 系统用户管理
 * @author shevliu
 * @email shevliu@gmail.com Jul 26, 2012 10:10:58 PM
 */
public class SysUserController extends Controller {

	private Log log = LogFactory.getLog(this.getClass());

	public void index() {
	    List<Tel> companys = Tel.dao.find("select company, city from tel_company");
	    
		String fromSql = "from sys_user where status=1";
		String userName = getPara("user_name");
		String userCity=getPara("user_city");
		if(StringUtils.isNotBlank(userName)){
			fromSql += " and user_name='"+userName+"' ";
		}
		if(StringUtils.isNotBlank(userCity)){
		    setAttr("user_city", userCity);
		    if(userCity.length()>2)
		        userCity=userCity.substring(0, 2);
		    for (Tel tel : companys)
            {
                if(tel.get("city").toString().substring(0, 2).equals(userCity)){
                    fromSql+=" and company='"+tel.getStr("company")+"' ";
                    break;
                }
            }
		    
		    
		}
		fromSql += " order by id desc";
		Page<SysUser> page = SysUser.dao.paginate(getParaToInt(0, 1), 30,
				"select * ", fromSql);
		
		
		setAttr("page", page);
		setAttr("companys", companys);
		render("sys_user_index.ftl");
	}

	public void add() {
		render("sys_user_add.ftl");
	}
	
	public void editSysUser() {
		int sysUserId = getParaToInt();
		setAttr("sysUser", SysUser.dao.findById(sysUserId));
		render("sys_user_edit.ftl");
	}
	
	public void saveEditSysUser() {
		/*SysUser sysUser = getModel(SysUser.class);
		sysUser.put("user_name", getPara("user_name"));
		sysUser.put("real_name", getPara("real_name"));
		sysUser.put("cell_phone", getPara("cell_phone"));
		sysUser.put("user_role", getPara("role"));
		sysUser.put("company", getPara("company"));
		sysUser.put("edit_user", this.getRequest().getSession().getAttribute("userName"));*/
		Db.update("update sys_user set user_name=?,real_name = ?,cell_phone = ?,user_role= ?, company = ?,edit_user = ? where id=?",
				getPara("user_name"),
				getPara("real_name"),
				getPara("cell_phone"),
				getPara("role"),
				getPara("company"),
				this.getRequest().getSession().getAttribute("userName"),
				getPara("id"));
		redirect("/sysUser");
	}

	public void save() {
		SysUser sysUser = getModel(SysUser.class);
		String password = getPara("password");
		sysUser.put("password", MD5Util.MD5(password));
		sysUser.put("user_name", getPara("user_name"));
		sysUser.put("real_name", getPara("real_name"));
		sysUser.put("cell_phone", getPara("cell_phone"));
		sysUser.put("user_role", getPara("role"));
		sysUser.put("company", getPara("company"));
		sysUser.put("edit_user",
				this.getRequest().getSession().getAttribute("userName"));
		sysUser.save();
		redirect("/sysUser");
	}

	public void editPWD() {
		setAttr("sysUser", SysUser.dao.findById(getParaToInt()));
		render("sys_user_password.ftl");
	}

	public void updatePWD() {
		int id = getParaToInt("id");
		String password = MD5Util.MD5(getPara("password"));
		Db.update("update sys_user set password=?,edit_user = ? where id=?",
				password,
				(String) this.getRequest().getSession()
						.getAttribute("userName"), id);
		redirect("/sysUser");
	}

	public void delete() {
		int id = getParaToInt(0);
		if (id == 1) {
			return; // admin不能删除
		}
		Db.update("update sys_user set status=0,edit_user = ? where id=?",
				(String) this.getRequest().getSession()
						.getAttribute("userName"), id);
		redirect("/sysUser");
	}
	
	public void telList() {
        String menuType=getRequest().getParameter("menuType");
		String sql = "SELECT *,(SELECT COUNT(*) FROM tel_company_message WHERE create_time >DATE_ADD(CURDATE(),INTERVAL -DAY(CURDATE())+1 DAY) AND create_time<LAST_DAY(CURDATE()) AND COMPANY=t.company) countMessage FROM tel_company t";
		/*String sql = " SELECT c.*, "+
					 " (SELECT u.real_name FROM sys_user u WHERE u.company=c.company LIMIT 1) real_name, "+
					 " (SELECT u.cell_phone FROM sys_user u WHERE u.company=c.company LIMIT 1) cell_phone "+
					 " FROM tel_company c ";*/
		List<Record> list = Db.find(sql);
//		for(Record rec:list)
//		{
//			int c=rec.getInt("company");
//			rec.set("companyname", getCompanyName(c));
//		}
//		
		
		setAttr("tellist", list);
        setAttr("menuType",menuType);
		render("sys_tel_company.ftl");
	}
	
	public void editPrice() {
		String company = getPara(0);
		setAttr("company",company);
		String sql = "select * from tel_price where company='"+company+"'";
		List<Record> list = Db.find(sql);
		setAttr("telPriceList", list);
		
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		render("sys_telcompany_add_price.ftl");
	}
	
	public void deletePrice() {
		int id = getParaToInt("id");
		String company = getPara("company");
		Db.update("delete from tel_price where id = ?", id);
		setAttr("company",company);
		String sql = "select * from tel_price where company='"+company+"'";
		List<Record> list = Db.find(sql);
		setAttr("telPriceList", list);
		
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("sys_telcompany_add_price.ftl");
	}
	
	public void timePriceSave() {
		String company = getPara("company");
		String startTime = getPara("startTime");
		String startMinutes = getPara("startMinutes");
		String endTime = getPara("endTime");
		String endMinutes = getPara("endMinutes");
		String initialPrice = getPara("initialPrice");
		String initialKm = getPara("initialKm");
		String overKm = getPara("overKm");
		String overPlusPrice = getPara("overPlusPrice");
		String priceRuleId = getPara("price_rule_id");
		String waitTime=getPara("waitTime");
		String waitFee=getPara("waitFee");
		
		//SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String startRunTime = startTime + ":" + startMinutes + ":00";
		String endRunTime = endTime + ":" + endMinutes + ":59";
		
		TelPrice tmp = getModel(TelPrice.class);
		tmp.put("company",company);
		tmp.put("startTime", startRunTime);
		tmp.put("endTime", endRunTime);
		tmp.put("initialPrice", initialPrice);
		tmp.put("initialKm", initialKm);
		tmp.put("overKm", overKm);
		tmp.put("overPlusPrice", overPlusPrice);
		tmp.put("price_rule_id", priceRuleId);
		tmp.put("waitFee", waitFee);
		tmp.put("waitTime", waitTime);
		tmp.save();
		setAttr("company",company);
		String sql = "select * from tel_price where company='"+company+"'";
		List<Record> list = Db.find(sql);
		setAttr("telPriceList", list);
		
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		render("sys_telcompany_add_price.ftl");
	}
	
	public void telAdd() {
		String citySql = "select * from b_city";
		String userRole = (String)getSession().getAttribute("userRole");
		String cityId = (String)getSession().getAttribute("cityId");
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			citySql = citySql + " where id="+cityId;
		}
		
		List<City> citys = City.dao.find(citySql);
		setAttr("citys", citys);
		render("sys_telcompany_add.ftl");
	}
	
	public void telEidt() {
		int id = getParaToInt(0);
		if (id == 0) {
			return; // admin不能删除
		}
		
		String citySql = "select * from b_city";
		String userRole = (String)getSession().getAttribute("userRole");
		String cityId = (String)getSession().getAttribute("cityId");
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			citySql = citySql + " where id="+cityId;
		}
		List<City> citys = City.dao.find(citySql);
		setAttr("citys", citys);
		
		String sql = "select * from tel_company where id=? ";
		Record rec = Db.findFirst(sql, id);
		
		setAttr("id", rec.getInt("id"));
		setAttr("newCityId", rec.getInt("new_city_id"));
		setAttr("tel", rec.getStr("tel"));
		setAttr("company", rec.getStr("company"));
		setAttr("companyname", rec.getStr("companyname"));
		setAttr("user_name", rec.getStr("user_name"));
		setAttr("user_pass", rec.getInt("user_pass"));
		setAttr("commissiontype", rec.getInt("commissiontype"));
//		setAttr("morningtime", rec.getStr("morningtime"));
//		setAttr("morningminutes", rec.getStr("morningminutes"));
//		setAttr("afternoontime", rec.getStr("afternoontime"));
//		setAttr("afternoonminutes", rec.getStr("afternoonminutes"));
		setAttr("fixedmoney", rec.getStr("fixedmoney"));
		setAttr("proportion", rec.getInt("proportion"));
		setAttr("lowerthanmoney", rec.getStr("lowerthanmoney"));
		setAttr("commissionmoney", rec.getStr("commissionmoney"));
		setAttr("daymoney", rec.getStr("daymoney"));
		setAttr("city_id", rec.getStr("city_id"));
		setAttr("call_proportion", rec.getInt("call_proportion"));
		if(rec.getInt("message_num") != null){
			setAttr("message_num", rec.getInt("message_num"));
		}
		setAttr("client_phone", rec.getStr("client_phone"));
		setAttr("driver_limit_amt", rec.getBigDecimal("driver_limit_amt"));
		setAttr("sun_company", rec.getStr("sun_company"));
		setAttr("city", (rec.getStr("city") != null?rec.getStr("city"):""));
		setAttr("price", (rec.getFloat("price") != null?rec.getFloat("price"):""));
		setAttr("safe_money", (rec.getFloat("safe_money") != null?rec.getFloat("safe_money"):0));
		render("sys_telcompany_edit.ftl");
	}
	
	public void telSave() {
		String tel = getPara("tel");
		String company = getPara("company");
		String companyName = getPara("companyName");
		String sun_company = getPara("sun_company");
		//String city = getPara("city");
		String newCityId = getPara("new_city_id");
		String price = getPara("price");
		String user_name = getPara("user_name");
		String user_phone = getPara("user_phone");
		int commissiontype = getParaToInt("commissiontype");
		int city_id = getParaToInt("new_city_id");
		int call_proportion = getParaToInt("call_proportion");
		String message_num = getPara("message_num");
		String client_phone = getPara("client_phone");
		String driver_limit_amt = getPara("driver_limit_amt");
//		String morningtime = getPara("morningtime");
//		String morningminutes = getPara("morningminutes");
//		String afternoontime = getPara("afternoontime");
//		String afternoonminutes = getPara("afternoonminutes");
		String fixedmoney = 0+"";
		String daymoney = 0+"";
		int proportion = 0;
		if(commissiontype == 1){
			fixedmoney = getPara("fixedmoney");
		}else if(commissiontype == 2){
			proportion = getParaToInt("proportion");
		}else if(commissiontype == 3){
			daymoney = getPara("daymoney");
		}
		String lowerthanmoney = getPara("lowerthanmoney");
		String commissionmoney = getPara("commissionmoney");
		float safemoney=Float.parseFloat(getPara("safe_money"));
		
		Tel tmp = getModel(Tel.class);
		
		tmp.put("companyname", companyName);
		tmp.put("sun_company", sun_company);
		tmp.put("tel", tel);
		tmp.put("company", company);
		tmp.put("commissiontype", commissiontype);
//		tmp.put("morningtime", morningtime);
//		tmp.put("morningminutes", morningminutes);
//		tmp.put("afternoontime", afternoontime);
//		tmp.put("afternoonminutes", afternoonminutes);
		tmp.put("fixedmoney", fixedmoney);
		tmp.put("proportion", proportion);
		tmp.put("daymoney", daymoney);
		tmp.put("lowerthanmoney", lowerthanmoney);
		tmp.put("commissionmoney", commissionmoney);
		setAttr("driver_limit_amt", driver_limit_amt);
		
		if(newCityId == null || "".equals(newCityId)){
			throw new RuntimeException("请选择所属城市");
		}
		City city = City.dao.findById(newCityId);
		tmp.put("new_city_id", city.getInt("id"));
		tmp.put("city", city.getStr("city_name"));
		tmp.put("price", price);
		tmp.put("user_name", user_name);
		tmp.put("user_phone", user_phone);
		tmp.put("city_id", city_id);
		tmp.put("call_proportion", call_proportion);
		if(!(message_num == null || "".equals(message_num))){
			tmp.put("message_num", message_num);
		}
		tmp.put("client_phone", client_phone);
		tmp.put("safe_money", safemoney);
		tmp.save();
		
		telList();
	}

		
	public void telEidtOK() {
		String userName = (String)getSession().getAttribute("userName");
		
		String id = getPara("id");
		String tel = getPara("tel");
		String company = getPara("company");
		String companyName = getPara("companyname");
		String sun_company = getPara("sun_company");
		//String city = getPara("city");
		String newCityId = getPara("new_city_id");
		String price = getPara("price");
		String user_name = getPara("user_name");
		String user_phone = getPara("user_phone");
		Integer commissiontype = getParaToInt("commissiontype");
		Integer city_id = getParaToInt("city_id");
		Integer call_proportion = getParaToInt("call_proportion");
		String message_num = getPara("message_num");
		String driver_limit_amt = getPara("driver_limit_amt");
		if(driver_limit_amt == null || "".equals(driver_limit_amt)){
			driver_limit_amt = "0";
		}
		if(message_num == null || "".equals(message_num)){
			message_num = "0";
		}
		String client_phone = getPara("client_phone");
//		String morningtime = getPara("morningtime");
//		String morningminutes = getPara("morningminutes");
//		String afternoontime = getPara("afternoontime");
//		String afternoonminutes = getPara("afternoonminutes");
		String fixedmoney = 0+"";
		String daymoney = 0+"";
		Integer proportion = 0;
		if(commissiontype == 1){
			fixedmoney = getPara("fixedmoney");
		}else if(commissiontype == 2){
			proportion = getParaToInt("proportion");
		}else if(commissiontype == 3){
			daymoney = getPara("daymoney");
		}
		String lowerthanmoney = getPara("lowerthanmoney");
		String commissionmoney = getPara("commissionmoney");
		float safemoney=Float.parseFloat(getPara("safe_money"));
		
		if(newCityId == null || "".equals(newCityId)){
			throw new RuntimeException("请选择所属城市");
		}
		City city = City.dao.findById(newCityId);
		
		String cityName = city.getStr("city_name");
		
		
		if("admin".equals(userName)){
			String sql = "update tel_company set tel=?,company=?,companyname=?,commissiontype=?,fixedmoney=?,proportion=?,daymoney=?,lowerthanmoney=?,commissionmoney=?,city=?,price=?,user_name=?,user_phone=?,city_id=?,call_proportion=?,sun_company=?,message_num=?,client_phone=?, new_city_id=? , driver_limit_amt= ? ,safe_money=? where id=?";
			Db.update(sql, tel, company, companyName,commissiontype,fixedmoney,proportion,daymoney,lowerthanmoney,commissionmoney,cityName,price,user_name,user_phone, city_id, call_proportion,sun_company,message_num,client_phone, newCityId,driver_limit_amt,safemoney,  id);
		}else{
			String sql = "update tel_company set tel=?,commissiontype=?,fixedmoney=?,proportion=?,daymoney=?,lowerthanmoney=?,commissionmoney=?,city=?,price=?,user_name=?,user_phone=?,call_proportion=?,client_phone=?, new_city_id=?, driver_limit_amt=?,safe_money=? where id=?";
			Db.update(sql, tel, commissiontype,fixedmoney,proportion,daymoney,lowerthanmoney,commissionmoney,cityName,price,user_name,user_phone, call_proportion,client_phone, newCityId,driver_limit_amt, safemoney,id);
		}
		
		telList();
	}	
	
	public void telDel() {
		
		int id = getParaToInt(0);
		if (id == 0) {
			return; // admin不能删除
		}

		Db.update("delete from tel_company where id = ?", id);
		
		telList();
	}	
	
	/*public void SetMyTel() {
		int company = getParaToInt("company");
		String myCompanyName=getCompanyName(company);
		getSession().setAttribute("myCompany", company);
		getSession().setAttribute("myCompanyName", myCompanyName);
		setAttr("ok", 1);
		
	    renderJson();
	}*/
	public void SetMyTel() {
		String company = getPara("company");
		Record rec = Db
				.findFirst(
						"select companyname FROM tel_company where company = '"+company+"'");
		String myCompanyName= rec.getStr("company");
		getSession().setAttribute("myCompany", company);
		getSession().setAttribute("myCompanyName", myCompanyName);
		setAttr("ok", 1);
		
	    renderJson();
	}
	
	
	public static String getCompanyName(int company)
	{
		String myCompanyName="其它公司";
		switch(company)
		{
			case 10:
				myCompanyName="	拇指";
				break;
			case 11:
				myCompanyName="福威";
				break;
			case 12:
				myCompanyName="渝通";
				break;
			case 13:
				myCompanyName="道宽";
				break;
				
				
			case 999:
				myCompanyName="其它公司";
				break;
			default:
				
		}
		return myCompanyName;
	}
	
	public static void main(String[] args){
		System.out.println(MD5Util.MD5("112233"));
	}
	
	public void lock(){
		String id=getPara();
		SysUser user=SysUser.dao.findById(id);
		user.set("lock", "1");
		user.update();
		redirect("/sysUser");
	}
	
	public void unlock(){
		String id=getPara();
		SysUser user=SysUser.dao.findById(id);
		user.set("lock", "0");
		user.update();
		redirect("/sysUser");
	}
	
}
